<template>
  <div>
    <van-nav-bar title="商品搜索" left-arrow @click-left="$router.go(-1)" />
    <van-search
      placeholder="请输入要搜索的商品"
      shape="round"
      v-model="keyword"
      @search="addHistory"
    >
    </van-search>

    <!-- 历史纪录列表 -->
    <div class="history" v-show="keyword == ''">
      <div class="history-head">
        <p>历史记录</p>
        <van-icon name="delete" @click="removeHistory"/>
      </div>
      <div class="history-list">
        <div class="history-list-item" v-for="(item,index) in $store.state.mobile.historyList" :key="index">{{item}}</div>
      </div>
    </div>
    <!-- 商品列表 -->
    <recommand :recommandList="searchList" v-show="keyword.length > 0" />
  </div>
</template>

<script>
import recommand from "../common/recommand";
export default {
  name: "",
  components: {
    recommand,
  },
  data() {
    return {
      list: [],
      keyword: "", //搜索的关键字
    };
  },
  mounted() {
    let url = this.$store.state.mobile.yxUrl;
    this.$axios.get(`${url}/shop/goods/list`).then((res) => {
      console.log(res.data);

      this.list = res.data;
    });
  },
  methods: {
    //添加历史纪录
    addHistory() {
      if(this.keyword == ""){
          return false;
      }
      this.$store.commit("addHistory", this.keyword);
      this.keyword = "";
    },

    removeHistory(){
        this.$store.commit('removeHistory');
    }
  },
  computed: {
    searchList() {
      let list = this.list;

      return list.filter((item) => {
        return item.name.indexOf(this.keyword) > -1;
      });
    },
  },
  watch: {},
};
</script>

<style lang="scss" scoped>
.history {
  width: 100%;
  padding: 10px;
  box-sizing: border-box;

  .history-head {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .history-list {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .history-list-item {
      width: 23%;
      margin: 2% 1%;
      background: #f0f0f0;
      padding: 10px 5px;
      box-sizing: border-box;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>